package com.letu.database.tenant;

import com.letu.core.businmodel.TenantIgnoreTable;
import com.letu.core.context.ContextUtil;
import com.letu.core.exception.BizException;
import com.letu.database.plugins.MultiTenantLineHandler;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.ValueListExpression;
import org.apache.commons.lang3.StringUtils;


/**
 * JsqlParserSupport打印语句在这个类
 */
@Slf4j
public class MybatisTenantLineHandler implements MultiTenantLineHandler {
    /**
     * 表名 线程共享
     */
//    private static final ThreadLocal<String> tableNameLoad = new ThreadLocal<>();
    @Override
    public Expression getTenantId() {
//        String tableName = tableNameLoad.get();
//        log.info("检测到表：" + tableName);
//        //租户id规则
//        Long tenantId = tenantRule(tableName);
//        return tenantId == null ? null : new LongValue(tenantId);

        if (StringUtils.isBlank(ContextUtil.getGameTag())) {
            throw BizException.wrap(-15, "MybatisTenantLineHandler is 租户ID不能为空", "projectId is null");
        }
        return new StringValue(ContextUtil.getGameTag());
    }


    @Override
    public String getTenantIdColumn() {
        return "game_tag";
    }

    @Override
    public boolean ignoreTable(String tableName) {
        boolean pan =TenantIgnoreTable.baseTable.contains(tableName);
        return pan;
    }


    @Override
    public ValueListExpression getTenantIdList() {
        if (StringUtils.isBlank(ContextUtil.getTenantIdList())) {
            return null;
        }
//        String tableName = tableNameLoad.get();
//        String resultDataScope = DataScopeHandler.queryTenantSystemScope(tableName);
//        List<Long> tenantIdList = JSONArray.parseArray(ContextUtil.getTenantIdList(), Long.class);
//        LongValue[] tenantIds = tenantIdList.stream().map(LongValue::new).toArray(LongValue[]::new);
//        ExpressionList expressionList = new ExpressionList(tenantIds);
//        ValueListExpression listExpression = new ValueListExpression().withExpressionList(expressionList);
//        return listExpression;
        return null;
    }
}
